package multiThread.ThreadPool;

import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *
 * </p>
 *
 * @author LovelyBigDuck
 * @date 2021/6/3 20:07
 */
public class ThreadPool {
    public static void main(String[] args) {
        int i = Runtime.getRuntime().availableProcessors();
        // IO密集型，将线程池的数量设置为cpu个数*2
        System.out.println("cpu:" + i);

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(8 * 2,
                200,
                500,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingDeque<>(1000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        System.out.println("线程任务的开始时间：" + LocalDateTime.now());
        for (int j = 0; j < 1000; j++) {
            int finalJ = j;
            threadPoolExecutor.execute(() -> {
                if (finalJ % 1000 == 0) {
                    System.out.println("当前线程:" + Thread.currentThread());
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        System.out.println("已经执行或正在执行的任务数：" + threadPoolExecutor.getTaskCount());
        System.out.println("曾经创建过的最大线程数：" + threadPoolExecutor.getLargestPoolSize());
        //System.out.println(threadPoolExecutor.isTerminated());
        threadPoolExecutor.shutdown();
        while (true) {
            if (threadPoolExecutor.isTerminated()) {
                System.out.println("线程任务执行结束，当前时间:" + LocalDateTime.now());
                break;
            }
        }
    }
}
